<template>
  <div class="blacklist-management bg-background text-foreground p-4">
    <h2 class="mb-4 text-2xl font-bold">黑名单管理</h2>
    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="人员" name="人员">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
          <QueryForm :model="search" :formItems="formItems" @search="searchBlacklist" @reset="resetSearch" />
        </div>

        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialog" class="btn btn-primary">新增</button>
          <button @click="deleteSelected" class="btn btn-destructive">
            删除
          </button>
          <button @click="openImportDialog" class="btn btn-secondary">导入</button>
          <button @click="exportData" class="btn btn-secondary">导出</button> -->
          <el-button type="primary" @click="openAddDialog" style="width: 75px; height: 30px;">新增</el-button>
          <el-button @click="deleteSelected" style="width: 75px; height: 30px;">删除</el-button>
          <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
        </div>

        <!-- Data Table -->
        <div class="bg-card text-card-foreground my-6 rounded shadow-md">
          <!-- <table class="min-w-full table-auto">
            <thead>
              <tr class="bg-muted text-muted-foreground text-sm leading-normal">
                <th class="px-6 py-3 text-left">
                  <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
                </th>
                <th class="table-header">序号</th>
                <th class="px-6 py-3 text-left">人员姓名</th>
                <th class="px-6 py-3 text-left">证件号码</th>
                <th class="px-6 py-3 text-left">人员类型</th>
                <th class="px-6 py-3 text-left">原因</th>
                <th class="px-6 py-3 text-left">禁止入场起始日期</th>
                <th class="px-6 py-3 text-left">预计解除日期</th>
                <th class="px-6 py-3 text-left">创建人</th>
                <th class="px-6 py-3 text-left">创建日期</th>
                <th class="px-6 py-3 text-left">备注</th>
                <th class="px-6 py-3 text-left">操作</th>
              </tr>
            </thead>
            <tbody class="text-sm">
              <tr v-for="(item, index) in displayedBlacklistData" :key="item.id"
                class="border-border hover:bg-muted/50 border-b">
                <td class="px-6 py-3 text-left">
                  <input type="checkbox" v-model="item.selected" class="checkbox" />
                </td>
                <td class="px-6 py-3 text-left">
                  {{ index + 1 }}
                </td>
                <td class="px-6 py-3 text-left">{{ item.name }}</td>
                <td class="px-6 py-3 text-left">{{ item.id_number }}</td>
                <td class="px-6 py-3 text-left">
                  {{ getBlacklistTypeText(item.blacklist_type) }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ item.reason }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ formatDateTime(item.start_time) }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ formatDateTime(item.end_time) }}
                </td>
                <td class="px-6 py-3 text-left">{{ item.created_by }}</td>
                <td class="px-6 py-3 text-left">{{ item.created_at }}</td>
                <td class="px-6 py-3 text-left">
                  {{ item.remark ? item.remark : '无' }}
                </td>
                <td class="px-6 py-3 text-left">
                  <button @click="editBlacklist(item)" class="btn btn-sm btn-secondary mr-2">
                    编辑
                  </button>
                  <button @click="open(item.id)" class="btn btn-sm btn-secondary">
                    解除
                  </button>
                </td>
              </tr>
            </tbody>
          </table> -->
          <el-table v-loading="loading" :data="displayedBlacklistData" style="width: 100%"
            @selection-change="handleSelectionChange" ref="tableRef" align="center" class="data-table"
            :header-cell-style="headerCellStyle" empty-text="暂无数据" :row-key="rowKey">
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" width="55" header-align="center" align="center">
              <template #default="scope">
                {{ startIndex + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="NAME" label="人员姓名" header-align="center" align="center"></el-table-column>
            <el-table-column min-width="90" prop="ID_NUMBER" label="证件号码" header-align="center"
              align="center"></el-table-column>
            <el-table-column prop="BLACKLIST_TYPE" label="人员类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="REASON" label="原因" header-align="center" align="center"></el-table-column>
            <el-table-column prop="START_TIME" label="禁止入场起始日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.START_TIME) }}
              </template>
            </el-table-column>
            <el-table-column prop="END_TIME" label="预计解除日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.END_TIME) }}
              </template>
            </el-table-column>
            <el-table-column prop="CREATED_BY" label="创建人" header-align="center" align="center"></el-table-column>
            <el-table-column prop="CREATED_AT" label="创建日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.CREATED_AT) }}
              </template>
            </el-table-column>
            <el-table-column prop="REMARK" label="备注" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editBlacklist(scope.row)" link>编辑</el-button>
                <el-button type="primary" size="small" @click="open(scope.row.ID)" link>解除</el-button>
                <!-- <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Pagination -->
        <!-- <Pagination v-if="blacklistData.length" :tableData="blacklistData" @alltabledata="alltabledata" /> -->
        <div
          class="flex items-center justify-between px-4 py-3 bg-card text-card-foreground border-t border-border sm:px-6">
          <div>
            <p class="text-sm text-muted-foreground">
              一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
            </p>
          </div>
          <div class="flex items-center space-x-2">
            <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
              上一页
            </button>
            <span class="text-sm text-muted-foreground">
              {{ currentPage }} / {{ totalPages }}
            </span>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
              :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
              下一页
            </button>
          </div>
        </div>
        <!-- Add/Edit Dialog -->
        <!-- <Teleport to="body">
          <div v-if="isAddDialogOpen || isEditDialogOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">
                {{ isEditDialogOpen ? '编辑黑名单' : '新增黑名单' }}
              </h3>
              <form @submit.prevent="handleSubmit">
                <div class="grid  grid-cols-2 gap-4">
                  <div>
                    <label for="name" class="text-muted-foreground block text-sm font-medium">人员姓名：</label>
                    <input type="text" id="name" v-model="formData.name" required class="input" />
                  </div>
                  <div>
                    <label for="idNumber" class="text-muted-foreground block text-sm font-medium">证件号码：</label>
                    <input type="text" id="idNumber" v-model="formData.id_number" required class="input" />
                  </div>
                  <div>
                    <label for="blacklistType" class="text-muted-foreground block text-sm font-medium">人员类型：</label>
                    <select id="blacklistType" v-model="formData.blacklist_type" required class="input">
                      <option value="1">企业内部人员</option>
                      <option value="2">园区工作人员</option>
                      <option value="3">承包商人员</option>
                      <option value="4">临时访客</option>
                      <option value="5">应急救援人员</option>
                      <option value="6">上级部分检查人员</option>
                      <option value="7">驾驶员</option>
                      <option value="8">押运员</option>
                      <option value="9">其他</option>
                    </select>
                  </div>
                  <div>
                    <label for="startTime" class="text-muted-foreground block text-sm font-medium">禁止入场起始日期：</label>
                    <input type="datetime-local" id="startTime" v-model="formData.start_time" required class="input" />
                  </div>
                  <div>
                    <label for="endTime" class="text-muted-foreground block text-sm font-medium">预计解除日期：</label>
                    <input type="datetime-local" id="endTime" v-model="formData.end_time" required class="input" />
                  </div>
                  <div>
                    <label for="reason" class="text-muted-foreground block text-sm font-medium">原因：</label>
                    <textarea id="reason" v-model="formData.reason" required class="input"></textarea>
                  </div>
                  <div>
                    <label for="remark" class="text-muted-foreground block text-sm font-medium">备注：</label>
                    <textarea id="remark" v-model="formData.remark" required class="input"></textarea>
                  </div>
                  <div>
                    <label for="createdBy" class="text-muted-foreground block text-sm font-medium">创建人：</label>
                    <input type="text" id="createdBy" v-model="formData.created_by" required class="input" />
                  </div>
                </div>
                <div class="mt-4 flex justify-end space-x-2">
                  <button type="button" @click="closeDialog" class="btn btn-secondary">
                    取消
                  </button>
                  <button type="submit" class="btn btn-primary">确认</button>
                </div>
              </form>
            </div>
          </div>
        </Teleport> -->
        <el-dialog class="dialog-from" v-model="isAddDialogOpen" :title="isDialogType == 'add' ? '新增黑名单' : '编辑黑名单'"
          width="900" destroy-on-close align-center>
          <div class="body-item">
            <div class="box-title">
              <div class="box-color"></div><strong>基本信息</strong>
            </div>
            <div class="box-content">
              <el-form :model="formData" label-width="auto" :rules="rules" ref="formRef">
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="人员姓名：" label-position="top" prop="NAME">
                      <el-input v-model="formData.NAME" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="证件号码：" label-position="top" prop="ID_NUMBER">
                      <el-input v-model="formData.ID_NUMBER" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="人员类型：" label-position="top" prop="BLACKLIST_TYPE">
                      <el-select v-model="formData.BLACKLIST_TYPE" placeholder="请选择" clearable>
                        <el-option label="企业内部人员" value="企业内部人员" />
                        <el-option label="园区工作人员" value="园区工作人员" />
                        <el-option label="承包商人员" value="承包商人员" />
                        <el-option label="临时访客" value="临时访客" />
                        <el-option label="应急救援人员" value="应急救援人员" />
                        <el-option label="上级部分检查人员" value="上级部分检查人员" />
                        <el-option label="驾驶员" value="驾驶员" />
                        <el-option label="押运员" value="押运员" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="禁止入场起始日期：" label-position="top" prop="START_TIME">
                      <input type="datetime-local" v-model="formData.START_TIME"
                        class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="预计解除日期：" label-position="top" prop="END_TIME">
                      <input type="datetime-local" v-model="formData.END_TIME"
                        class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"></el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="24">
                    <el-form-item label="原因：" label-position="top" prop="REASON">
                      <el-input type="textarea" v-model="formData.REASON"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="24">
                    <el-form-item label="备注：" label-position="top" prop="REMARK">
                      <el-input type="textarea" v-model="formData.REMARK"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="创建人：" label-position="top" prop="CREATED_BY">
                      <el-input v-model="formData.CREATED_BY" placeholder="请输入"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"></el-col>
                  <el-col :span="8"></el-col>
                </el-row>
              </el-form>
            </div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmit">确认</el-button>
              <el-button @click="closeDialog">
                取消
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- Import Dialog -->
        <Teleport to="body">
          <div v-if="isImportDialogOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[400px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">导入黑名单</h3>
              <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
                class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
              <div class="flex justify-end space-x-2">
                <button @click="closeImportDialog" class="btn btn-secondary">
                  取消
                </button>
                <button @click="importData" class="btn btn-primary">
                  导入
                </button>
              </div>
            </div>
          </div>
        </Teleport>

        <!-- View Details Dialog -->
        <Teleport to="body">
          <div v-if="isViewDialogOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">查看黑名单详情</h3>
              <div v-if="viewingItem">
                <p><strong>姓名：</strong>{{ viewingItem.name }}</p>
                <p><strong>身份证号：</strong>{{ viewingItem.id_number }}</p>
                <p>
                  <strong>黑名单类型：</strong>{{ getBlacklistTypeText(viewingItem.blacklist_type) }}
                </p>
                <p>
                  <strong>开始时间：</strong>{{ formatDateTime(viewingItem.start_time) }}
                </p>
                <p>
                  <strong>结束时间：</strong>{{ formatDateTime(viewingItem.end_time) }}
                </p>
                <p><strong>原因：</strong>{{ viewingItem.reason }}</p>
                <p><strong>创建人：</strong>{{ viewingItem.created_by }}</p>
                <p>
                  <strong>创建日期：</strong>{{ formatDateTime(viewingItem.created_at) }}
                </p>
                <p><strong>更新人：</strong>{{ viewingItem.updated_by }}</p>
                <p>
                  <strong>更新时间：</strong>{{ formatDateTime(viewingItem.updated_at) }}
                </p>
              </div>
              <div class="mt-4 flex justify-end">
                <button @click="closeViewDialog" class="btn btn-secondary">
                  关闭
                </button>
              </div>
            </div>
          </div>
        </Teleport>
      </el-tab-pane>
      <el-tab-pane label="车辆" name="车辆">
        <!-- Search Bar -->
        <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">

          <QueryForm :model="searchCar" :formItems="formItemsCar" @search="searchBlacklistCar"
            @reset="resetSearchCar" />
        </div>

        <!-- Action Buttons -->
        <div class="mb-4 space-x-2">
          <!-- <button @click="openAddDialogCar" class="btn btn-primary">
            新增
          </button>
          <button @click="deleteCarSelected" class="btn btn-destructive">
            删除
          </button> -->
          <el-button type="primary" @click="openAddDialogCar" style="width: 75px; height: 30px;">新增</el-button>
          <el-button @click="deleteCarSelected" style="width: 75px; height: 30px;">删除</el-button>
          <el-button @click="exportDataCar" style="width: 75px; height: 30px;">导出</el-button>
          <!-- <button @click="openImportDialog" class="btn btn-secondary">导入</button>
      <button @click="exportData" class="btn btn-secondary">导出</button> -->
        </div>

        <!-- Data Table -->
        <div class="bg-card text-card-foreground my-6 rounded shadow-md">
          <!-- <table class="min-w-full table-auto">
            <thead>
              <tr class="bg-muted text-muted-foreground text-sm leading-normal">
                <th class="px-6 py-3 text-left">
                  <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
                </th>
                <th class="table-header">序号</th>
                <th class="px-6 py-3 text-left">车牌号码</th>
                <th class="px-6 py-3 text-left">驾驶员姓名</th>
                <th class="px-6 py-3 text-left">车辆类型</th>
                <th class="px-6 py-3 text-left">原因</th>
                <th class="px-6 py-3 text-left">禁止入场起始日期</th>
                <th class="px-6 py-3 text-left">预计解除日期</th>
                <th class="px-6 py-3 text-left">创建人</th>
                <th class="px-6 py-3 text-left">创建日期</th>
                <th class="px-6 py-3 text-left">备注</th>
                <th class="px-6 py-3 text-left">操作</th>
              </tr>
            </thead>
            <tbody class="text-sm">
              <tr v-for="(item, index) in displayedBlackcarData" :key="item.id"
                class="border-border hover:bg-muted/50 border-b">
                <td class="px-6 py-3 text-left">
                  <input type="checkbox" v-model="item.selected" class="checkbox" />
                </td>
                <td class="px-6 py-3 text-left">
                  {{ index + 1 }}
                </td>
                <td class="px-6 py-3 text-left">{{ item.PLATE_NUMBER }}</td>
                <td class="px-6 py-3 text-left">{{ item.DRIVER_NAME }}</td>
                <td class="px-6 py-3 text-left">
                  {{ item.VEHICE_TYPE }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ item.REASON }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ formatDateTime(item.START_TIME) }}
                </td>
                <td class="px-6 py-3 text-left">
                  {{ formatDateTime(item.END_TIME) }}
                </td>
                <td class="px-6 py-3 text-left">{{ item.CREATED_BY }}</td>
                <td class="px-6 py-3 text-left">{{ formatDateTime(item.CREATED_AT) }}</td>
                <td class="px-6 py-3 text-left">
                  {{ (item.STAMP) }}
                </td>
                <td class="px-6 py-3 text-left">
                  <button @click="editBlacklistCar(item)" class="btn btn-sm btn-secondary mr-2">
                    编辑
                  </button>
                  <button @click="openCar(item.ID)" class="btn btn-sm btn-secondary">
                    解除
                  </button>
                </td>
              </tr>
            </tbody>
          </table> -->
          <el-table v-loading="loading" :data="displayedBlackcarData" style="width: 100%"
            @selection-change="handleSelectionCarChange" ref="tableRefCar" align="center" class="data-table"
            :header-cell-style="headerCellStyle" empty-text="暂无数据" :row-key="rowKey">
            <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
            <el-table-column label="序号" width="55" header-align="center" align="center">
              <template #default="scope">
                {{ startIndexCar + scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="PLATE_NUMBER" label="车牌号码" header-align="center" align="center"></el-table-column>
            <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
            <el-table-column prop="VEHICE_TYPE" label="车辆类型" header-align="center" align="center"></el-table-column>
            <el-table-column prop="REASON" label="原因" header-align="center" align="center"></el-table-column>
            <el-table-column prop="START_TIME" label="禁止入场起始日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.START_TIME) }}
              </template>
            </el-table-column>
            <el-table-column prop="END_TIME" label="预计解除日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.END_TIME) }}
              </template>
            </el-table-column>
            <el-table-column prop="CREATED_BY" label="创建人" header-align="center" align="center"></el-table-column>
            <el-table-column prop="CREATED_AT" label="创建日期" header-align="center" align="center">
              <template #default="scope">
                {{ formatDateTime(scope.row.CREATED_AT) }}
              </template>
            </el-table-column>
            <el-table-column prop="STAMP" label="备注" header-align="center" align="center"></el-table-column>
            <el-table-column label="操作" header-align="center" align="center">
              <template #default="scope">
                <el-button type="primary" size="small" @click="editBlacklistCar(scope.row)" link>编辑</el-button>
                <el-button type="primary" size="small" @click="openCar(scope.row.ID)" link>解除</el-button>
                <!-- <el-button type="primary" size="small" @click="viewDetails(scope.row)" link>查看</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- Pagination -->
        <Pagination v-if="blacklistCar.length" :tableData="blacklistCar" @alltabledata="alltabledatacar" />
        <!-- Add/Edit Dialog -->
        <!-- <Teleport to="body">
          <div v-if="isAddDialogCarOpen || isEditDialogCarOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">
                {{ isEditDialogCarOpen ? '编辑黑名单' : '新增黑名单' }}
              </h3>
              <form @submit.prevent="handleSubmitCar">
                <div class="grid  grid-cols-2 gap-4">
                  <div>
                    <label for="name" class="text-muted-foreground block text-sm font-medium">驾驶员姓名：</label>
                    <input type="text" id="name" v-model="formCarData.DRIVER_NAME" required class="input" />
                  </div>
                  <div>
                    <label for="idNumber" class="text-muted-foreground block text-sm font-medium">车牌号码：</label>
                    <input type="text" id="idNumber" v-model="formCarData.PLATE_NUMBER" required class="input" />
                  </div>
                  <div>
                    <label for="blacklistType" class="text-muted-foreground block text-sm font-medium">车辆类型：</label>
                    <select id="blacklistType" v-model="formCarData.VEHICE_TYPE" required class="input">
                      <option value="普货车">普货车</option>
                      <option value="社会车辆">社会车辆</option>
                      <option value="其他">其他</option>
                    </select>
                  </div>
                  <div>
                    <label for="startTime" class="text-muted-foreground block text-sm font-medium">禁止入场起始日期：</label>
                    <input type="datetime-local" id="startTime" v-model="formCarData.START_TIME" required
                      class="input" />
                  </div>
                  <div>
                    <label for="endTime" class="text-muted-foreground block text-sm font-medium">预计解除日期：</label>
                    <input type="datetime-local" id="endTime" v-model="formCarData.END_TIME" required class="input" />
                  </div>
                  <div>
                    <label for="reason" class="text-muted-foreground block text-sm font-medium">原因：</label>
                    <textarea id="reason" v-model="formCarData.REASON" required class="input"></textarea>
                  </div>
                  <div>
                    <label for="remark" class="text-muted-foreground block text-sm font-medium">备注：</label>
                    <textarea id="remark" v-model="formCarData.STAMP" required class="input"></textarea>
                  </div>
                  <div>
                    <label for="createdBy" class="text-muted-foreground block text-sm font-medium">创建人：</label>
                    <input type="text" id="createdBy" v-model="formCarData.CREATED_BY" required class="input" />
                  </div>
                </div>
                <div class="mt-4 flex justify-end space-x-2">
                  <button type="button" @click="closeDialog" class="btn btn-secondary">
                    取消
                  </button>
                  <button type="submit" class="btn btn-primary">确认</button>
                </div>
              </form>
            </div>
          </div>
        </Teleport> -->
        <el-dialog class="dialog-from" v-model="isAddDialogCarOpen"
          :title="isDialogTypeCar == 'add' ? '新增车辆黑名单' : '编辑车辆黑名单'" width="900" destroy-on-close align-center>
          <div class="body-item">
            <div class="box-title">
              <div class="box-color"></div><strong>基本信息</strong>
            </div>
            <div class="box-content">
              <el-form :model="formCarData" label-width="auto" :rules="rules" ref="formCarRef">
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="驾驶员姓名：" label-position="top" prop="DRIVER_NAME">
                      <el-input v-model="formCarData.DRIVER_NAME" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="车牌号码：" label-position="top" prop="PLATE_NUMBER">
                      <el-input v-model="formCarData.PLATE_NUMBER" placeholder="请输入" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="车辆类型：" label-position="top" prop="VEHICE_TYPE">
                      <el-select v-model="formCarData.VEHICE_TYPE" placeholder="请选择" clearable>
                        <el-option label="普货车" value="普货车" />
                        <el-option label="社会车辆" value="社会车辆" />
                        <el-option label="其他" value="其他" />
                      </el-select>
                    </el-form-item>
                  </el-col>

                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="禁止入场起始日期：" label-position="top" prop="START_TIME">
                      <input type="datetime-local" v-model="formCarData.START_TIME"
                        class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="预计解除日期：" label-position="top" prop="END_TIME">
                      <input type="datetime-local" v-model="formCarData.END_TIME"
                        class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"></el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="24">
                    <el-form-item label="原因：" label-position="top" prop="REASON">
                      <el-input type="textarea" v-model="formCarData.REASON"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="24">
                    <el-form-item label="备注：" label-position="top" prop="STAMP">
                      <el-input type="textarea" v-model="formCarData.STAMP"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="80" class="row-item">
                  <el-col :span="8">
                    <el-form-item label="创建人：" label-position="top" prop="CREATED_BY">
                      <el-input v-model="formCarData.CREATED_BY" placeholder="请输入"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8"></el-col>
                  <el-col :span="8"></el-col>
                </el-row>
              </el-form>
            </div>
          </div>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="handleSubmitCar">确认</el-button>
              <el-button @click="closeDialog">
                取消
              </el-button>
            </div>
          </template>
        </el-dialog>

        <!-- Import Dialog -->
        <Teleport to="body">
          <div v-if="isImportDialogOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[400px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">导入黑名单</h3>
              <input type="file" @change="handleFileUpload" accept=".xlsx, .xls"
                class="text-muted-foreground file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 mb-4 block w-full text-sm file:mr-4 file:rounded-full file:border-0 file:px-4 file:py-2 file:text-sm file:font-semibold" />
              <div class="flex justify-end space-x-2">
                <button @click="closeImportDialog" class="btn btn-secondary">
                  取消
                </button>
                <button @click="importData" class="btn btn-primary">
                  导入
                </button>
              </div>
            </div>
          </div>
        </Teleport>

        <!-- View Details Dialog -->
        <Teleport to="body">
          <div v-if="isViewDialogOpen"
            class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
            <div class="bg-card text-card-foreground w-[500px] rounded-lg p-5 shadow-xl">
              <h3 class="mb-4 text-lg font-bold">查看黑名单详情</h3>
              <div v-if="viewingItem">
                <p><strong>姓名：</strong>{{ viewingItem.name }}</p>
                <p><strong>身份证号：</strong>{{ viewingItem.id_number }}</p>
                <p>
                  <strong>黑名单类型：</strong>{{ getBlacklistTypeText(viewingItem.blacklist_type) }}
                </p>
                <p>
                  <strong>开始时间：</strong>{{ formatDateTime(viewingItem.start_time) }}
                </p>
                <p>
                  <strong>结束时间：</strong>{{ formatDateTime(viewingItem.end_time) }}
                </p>
                <p><strong>原因：</strong>{{ viewingItem.reason }}</p>
                <p><strong>创建人：</strong>{{ viewingItem.created_by }}</p>
                <p>
                  <strong>创建日期：</strong>{{ formatDateTime(viewingItem.created_at) }}
                </p>
                <p><strong>更新人：</strong>{{ viewingItem.updated_by }}</p>
                <p>
                  <strong>更新时间：</strong>{{ formatDateTime(viewingItem.updated_at) }}
                </p>
              </div>
              <div class="mt-4 flex justify-end">
                <button @click="closeViewDialog" class="btn btn-secondary">
                  关闭
                </button>
              </div>
            </div>
          </div>
        </Teleport>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
import * as XLSX from 'xlsx'
import { ElMessage, ElMessageBox, ElTabs, ElTabPane } from 'element-plus'

const { proxy } = getCurrentInstance()

const apiBaseUrl = computed(() => {
  return proxy.$currentUrl + '/api/blacklist'
})

const search = ref({
  NAME: '',
  BLACKLIST_TYPE: '',
})
const searchCar = ref({
  PLATE_NUMBER: '',
  DRIVER_NAME: '',
  VEHICE_TYPE: '',
})
const activeName = ref('人员')
const handleClick = (tab, event) => {
  if (tab == '人员') {
    searchBlacklist()
  } else if (tab == '车辆') {
    allBlacklistCar()
  }
}
const blacklistData = ref([])
const blacklistCar = ref([])

const selectAll = ref(false)
const isAddDialogOpen = ref(false)
const isAddDialogCarOpen = ref(false)
const isImportDialogOpen = ref(false)
const isEditDialogOpen = ref(false)
const isEditDialogCarOpen = ref(false)
const isViewDialogOpen = ref(false)
const blacklistTypeList = ref({
  1: '企业内部人员',
  2: '园区工作人员',
  3: '承包商人员',
  4: '临时访客',
  5: '应急救援人员',
  6: '上级部分检查人员',
  7: '驾驶员',
  8: '押运员',
  9: '其他',
})


const formItems = ref([

  {
    label: '人员姓名：',
    model: 'NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '人员类型：',
    model: 'BLACKLIST_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '企业内部人员', value: '企业内部人员' },
      { label: '园区工作人员', value: '园区工作人员' },
      { label: '承包商人员', value: '承包商人员' },
      { label: '临时访客', value: '临时访客' },
      { label: '应急教授人员', value: '应急教授人员' },
      { label: '上级部门检查人员', value: '上级部门检查人员' },
      { label: '管理员', value: '管理员' },
      { label: '押运员', value: '押运员' },
      { label: '其他', value: '其他' },

    ],
  },

])

const formItemsCar = ref([
  {
    label: '车牌号码：',
    model: 'PLATE_NUMBER',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '驾驶员姓名：',
    model: 'DRIVER_NAME',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '车辆类型：',
    model: 'VEHICE_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '普货车', value: '普货车' },
      { label: '社会车辆', value: '社会车辆' },
      { label: '其他', value: '其他' },
    ],
  },

])

const formData = ref({
  ID: null,
  NAME: '',
  ID_NUMBER: '',
  BLACKLIST_TYPE: '',
  START_TIME: '',
  END_TIME: '',
  REASON: '',
  CREATED_AT: '',
  CREATED_BY: '',
  REMARK: '',
})
const formCarData = ref({
  ID: '',
  PLATE_NUMBER: '',
  DRIVER_NAME: '',
  VEHICE_TYPE: '',
  CREATED_BY: '',
  CREATED_AT: '',
  END_TIME: '',
  START_TIME: '',
  STAMP: '',
  REASON: '',
  UPDATED_AT: ''
})
const viewingItem = ref(null)
const importFile = ref(null)

const currentPage = ref(1)
const pageSize = ref(10)
const totalItems = computed(() => blacklistData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))
const startIndex = computed(() => (currentPage.value - 1) * pageSize.value)

const currentPageCar = ref(1)
const pageSizeCar = ref(10)
const totalItemsCar = computed(() => blacklistCar.value.length)
const totalPagesCar = computed(() => Math.ceil(totalItemsCar.value / pageSizeCar.value))
const startIndexCar = computed(() => (currentPageCar.value - 1) * pageSizeCar.value)
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const loading = ref(false);
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--
}
const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++
}
const tableRef = ref(null)
const tableRefCar = ref(null)
const selectedIds = ref([])
const selectedCarIds = ref([])
const rowKey = (row) => row.id;
const handleSelectionChange = (selected) => {
  selectedIds.value = selected;
};
const handleSelectionCarChange = (selected) => {
  selectedCarIds.value = selected;
};
const alltabledata = (data) => {
  displayedBlacklistData.value = data
}
const alltabledatacar = (data) => {
  displayedBlackcarData.value = data
}
const displayedBlackcarData = computed(() => {
  const start = (currentPageCar.value - 1) * pageSize.value
  const end = start + pageSizeCar.value
  return blacklistCar.value.slice(start, end)
})
const displayedBlacklistData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return blacklistData.value.slice(start, end)
})

const searchBlacklist = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: search.value,
    })

    blacklistData.value = response.data.map((item) => ({
      ...item,
      selected: false,
    }))

  } catch (error) {
    console.error('搜索黑名单记录失败:', error)
    alert(
      '搜索黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
  loading.value = false
}
const searchBlacklistCar = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search/vehicles`, {
      params: searchCar.value,
    })

    blacklistCar.value = response.data.map((item) => ({
      ...item,
      selected: false,
    }))
  } catch (error) {
    console.error('搜索黑名单记录失败:', error)
    alert(
      '搜索黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const rules = reactive({
  NAME: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' },
  ],
  ID_NUMBER: [
    { required: true, message: '请输入证件号码', trigger: 'blur' },
  ],
  BLACKLIST_TYPE: [
    { required: true, message: '请选择人员类型', trigger: 'change' },
  ],
  START_TIME: [
    { required: true, message: '请选择禁止入场起始日期', trigger: 'change' },
  ],
  END_TIME: [
    { required: true, message: '请选择预计解除日期', trigger: 'change' },
  ],
  REASON: [
    { required: true, message: '请输入原因', trigger: 'blur' },
  ],
  REMARK: [
    { required: true, message: '请输入备注', trigger: 'blur' },
  ],
  CREATED_BY: [
    { required: true, message: '请输入创建人', trigger: 'blur' },
  ],
})
const allBlacklistCar = async () => {
  try {
    const response = await axios.get(`${apiBaseUrl.value}/search/vehicles`)
    // {
    //   params: searchCar.value,
    // }
    blacklistCar.value = response.data.map((item) => ({
      ...item,
      selected: false,
    }))
  } catch (error) {
    console.error('搜索黑名单记录失败:', error)
    alert(
      '搜索黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const resetSearch = () => {
  search.value = {
    NAME: '',
    BLACKLIST_TYPE: '',
  }
  searchBlacklist()
}
const resetSearchCar = () => {
  searchCar.value = {
    PLATE_NUMBER: '',
    DRIVER_NAME: '',
    VEHICE_TYPE: '',
  }
  allBlacklistCar()
}

const addNewBlacklistEntry = async () => {
  try {
    // formData.value.created_by = 'current_user'; // 替换为实际的用户信息
    formData.value.CREATED_AT = new Date().toISOString().slice(0, 16) // 设置当前时间
    const response = await axios.post(apiBaseUrl.value, formData.value)
    alert(response.data.message || '创建黑名单记录成功')
    closeDialog()
    await searchBlacklist()
  } catch (error) {
    console.error('创建黑名单记录失败:', error)
    alert(
      '创建黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const addNewBlacklistCarEntry = async () => {
  try {
    // formData.value.created_by = 'current_user'; // 替换为实际的用户信息
    formCarData.value.CREATED_AT = new Date().toISOString().slice(0, 16) // 设置当前时间
    console.log(formCarData.value)
    const response = await axios.post(apiBaseUrl.value + '/vehicles', formCarData.value)
    alert(response.data.message || '创建黑名单记录成功')
    closeDialog()
    await allBlacklistCar()
  } catch (error) {
    console.error('创建黑名单记录失败:', error)
    alert(
      '创建黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const deleteSelected = async () => {
  // const selectedIds = blacklistData.value
  //   .filter((item) => item.selected)
  //   .map((item) => item.id)
  if (selectedIds.value.length === 0) {
    alert('请至少选择一条记录进行删除')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(
        selectedIds.value.map((item) => axios.delete(`${apiBaseUrl.value}/${item.ID}`)),
      )
      alert('删除成功')
      selectedIds.value = []
      if (tableRef.value) {
        tableRef.value.clearSelection();
      }
      await searchBlacklist()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}
const formRef = ref(null)
const formCarRef = ref(null)
const deleteCarSelected = async () => {
  // const selectedIdss = blacklistCar.value
  //   .filter((item) => item.selected)
  //   .map((item) => item.ID)
  if (selectedCarIds.value.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedCarIds.value.length} 条记录吗？`)) {
    try {
      await Promise.all(
        selectedCarIds.value.map((item) => axios.delete(`${apiBaseUrl.value}/vehicles/${item.ID}`)),
      )
      alert('删除成功')
      selectedCarIds.value = []
      if (tableRefCar.value) {
        tableRefCar.value.clearSelection();
      }
      await allBlacklistCar()
    } catch (error) {
      console.error('删除记录失败:', error)
      alert(
        '删除记录失败: ' + (error.response?.data?.message || error.message),
      )
    }
  }
}
const updateBlacklistEntry = async () => {
  try {
    // formData.value.updated_by = 'current_user'; // 替换为实际的用户信息
    formData.value.UPDATED_AT = new Date().toISOString().slice(0, 16) // 设置当前时间
    const response = await axios.put(
      `${apiBaseUrl.value}/${formData.value.ID}`,
      formData.value,
    )
    alert(response.data.message || '更新黑名单记录成功')
    closeDialog()
    await searchBlacklist()
  } catch (error) {
    console.error('更新黑名单记录失败:', error)
    alert(
      '更新黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const updateBlacklistCarEntry = async () => {

  try {
    // formData.value.updated_by = 'current_user'; // 替换为实际的用户信息
    formCarData.value.updated_at = new Date().toISOString().slice(0, 16) // 设置当前时间
    const response = await axios.put(
      `${apiBaseUrl.value}/vehicles/${formCarData.value.ID}`,
      formCarData.value,
    )
    alert(response.data.message || '更新黑名单记录成功')
    closeDialog()
    await allBlacklistCar()
  } catch (error) {
    console.error('更新黑名单记录失败:', error)
    alert(
      '更新黑名单记录失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const exportDataCar = () => {
  const dataToExport = blacklistCar.value.map((item) => ({
    车牌号码: item.PLATE_NUMBER,
    驾驶员姓名: item.DRIVER_NAME,
    车辆类型: item.VEHICE_TYPE,
    原因: item.REASON,
    禁止入场起始日期: formatDateTime(item.START_TIME),
    预计解除日期: formatDateTime(item.END_TIME),
    创建人: item.CREATED_BY,
    创建日期: formatDateTime(item.CREATED_AT),
    备注: item.STAMP,
    // 通行抓拍: getPassageTypeText(item.PASS_IMG),
  }))
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '黑名单车辆记录')

  // 生成二进制字符串作为文件内容
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为Blob对象
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '黑名单车辆记录.xlsx'
  link.click()
}
// 辅助函数：将字符串转换为ArrayBuffer
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}
const exportData = () => {
  // const dataToExport = blacklistData.value.map(
  //   ({ id, selected, ...rest }) => rest,
  // )
  // console.log(dataToExport)
  // const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  // const workbook = XLSX.utils.book_new()
  // XLSX.utils.book_append_sheet(workbook, worksheet, '黑名单人员数据')
  // const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
  // const data = new Blob([excelBuffer], {
  //   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  // })
  // const link = document.createElement('a')
  // link.href = window.URL.createObjectURL(data)
  // link.download = '黑名单人员数据.xlsx'
  // link.click()
  const dataToExport = blacklistData.value.map((item) => ({
    人员姓名: item.NAME,
    证件号码: item.ID_NUMBER,
    人员类型: item.BLACKLIST_TYPE,
    原因: item.REASON,
    禁止入场起始日期: formatDateTime(item.START_TIME),
    预计解除日期: formatDateTime(item.END_TIME),
    创建人: item.CREATED_BY,
    创建日期: formatDateTime(item.CREATED_AT),
    备注: item.REMARK,
    // 通行抓拍: getPassageTypeText(item.PASS_IMG),
  }))
  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '黑名单人员记录')

  // 生成二进制字符串作为文件内容
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为Blob对象
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '黑名单人员记录.xlsx'
  link.click()
}

const importData = async () => {
  if (!importFile.value) {
    alert('请选择要导入的文件')
    return
  }
  const formData = new FormData()
  formData.append('file', importFile.value)
  try {
    const response = await axios.post(`${apiBaseUrl.value}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    alert(response.data.message || '导入成功')
    closeImportDialog()
    await searchBlacklist()
  } catch (error) {
    console.error('导入失败:', error)
    alert('导入失败: ' + (error.response?.data?.message || error.message))
  }
}

const openAddDialog = () => {
  isAddDialogOpen.value = true
  isDialogType.value = 'add'
  formData.value = {
    ID: null,
    NAME: '',
    ID_NUMBER: '',
    BLACKLIST_TYPE: '',
    START_TIME: '',
    END_TIME: '',
    REASON: '',
    CREATED_AT: '',
    CREATED_BY: '',
    REMARK: '',
  }
}
const openAddDialogCar = () => {
  isAddDialogCarOpen.value = true
  formCarData.value = {
    ID: '',
    PLATE_NUMBER: '',
    DRIVER_NAME: '',
    VEHICE_TYPE: '',
    CREATED_BY: '',
    CREATED_AT: '',
    END_TIME: '',
    START_TIME: '',
    STAMP: '',
    REASON: '',
    UPDATED_AT: ''
  }
}
const open = (id) => {
  ElMessageBox.confirm('请确认您希望继续解除操作。', '解除提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    center: true,
  })
    .then(async () => {
      await axios.delete(`${apiBaseUrl.value}/${id}`)
      ElMessage({
        type: 'success',
        message: '解除成功',
      })
      searchBlacklist()
    })
    .catch(() => { })
}
const openCar = (id) => {
  ElMessageBox.confirm('请确认您希望继续解除操作。', '解除提示', {
    cancelButtonText: '取消',
    confirmButtonText: '确认',
    center: true,
  })
    .then(async () => {

      await axios.delete(`${apiBaseUrl.value}/vehicles/${id}`)
      ElMessage({
        type: 'success',
        message: '解除成功',
      })
      allBlacklistCar()
    })
    .catch(() => { })
}
const closeDialog = () => {
  isAddDialogOpen.value = false
  isEditDialogOpen.value = false
  isAddDialogCarOpen.value = false
  isEditDialogCarOpen.value = false
}

const openImportDialog = () => {
  isImportDialogOpen.value = true
}

const closeImportDialog = () => {
  isImportDialogOpen.value = false
  importFile.value = null
}

const editBlacklist = (item) => {
  formData.value = { ...item }
  if (formData.value.START_TIME) {
    formData.value.START_TIME = formatDateTimeForInput(
      formData.value.START_TIME,
    )
  }
  if (formData.value.END_TIME) {
    formData.value.END_TIME = formatDateTimeForInput(formData.value.END_TIME)
  }
  if (formData.value.CREATED_AT) {
    formData.value.CREATED_AT = formatDateTimeForInput(
      formData.value.CREATED_AT,
    )
  }
  isAddDialogOpen.value = true
  isDialogType.value = 'edit'
}
const isDialogType = ref('add')
const editBlacklistCar = (item) => {
  formCarData.value.ID = item.ID
  formCarData.value.PLATE_NUMBER = item.PLATE_NUMBER
  formCarData.value.DRIVER_NAME = item.DRIVER_NAME
  formCarData.value.VEHICE_TYPE = item.VEHICE_TYPE
  formCarData.value.CREATED_BY = item.CREATED_BY
  formCarData.value.END_TIME = item.END_TIME
  formCarData.value.START_TIME = item.START_TIME
  formCarData.value.STAMP = item.STAMP
  formCarData.value.REASON = item.REASON

  if (formCarData.value.START_TIME) {
    formCarData.value.START_TIME = formatDateTimeForInput(
      formCarData.value.START_TIME,
    )
  }
  if (formCarData.value.END_TIME) {
    formCarData.value.END_TIME = formatDateTimeForInput(formCarData.value.END_TIME)
  }
  // if (formCarData.value.created_at) {
  //   formCarData.value.created_at = formatDateTimeForInput(
  //     formCarData.value.created_at,
  //   )
  // }
  isDialogTypeCar.value = 'edit'
  isAddDialogCarOpen.value = true
}
const isDialogTypeCar = ref('add')
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}
const viewDetails = (item) => {
  // viewingItem.value = { ...item };
  // isViewDialogOpen.value = true;
}

const closeViewDialog = () => {
  isViewDialogOpen.value = false
  viewingItem.value = null
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  blacklistData.value.forEach((item) => (item.selected = selectAll.value))
}



const getBlacklistTypeText = (type) => {
  // return type === '1' ? '临时黑名单' : '永久黑名单';
  return blacklistTypeList.value[type] || '未知类型'
}

const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}

const handleSubmit = () => {
  // if (formData.value.ID) {
  //   updateBlacklistEntry()
  // } else {
  //   addNewBlacklistEntry()
  // }
  try {
    formRef.value.validate(async (valid) => {
      if (valid) {
        if (!formData.value.ID) {
          addNewBlacklistEntry()
          alert(response.data.message || '创建黑名单成功')
        } else {
          updateBlacklistEntry()
          alert(response.data.message || '更新黑名单成功')
        }
        await loadData()
      }
    })
  } catch (error) {
    console.error('创建危险化学品失败:', error)
    alert(
      '创建危险化学品失败: ' + (error.response?.data?.message || error.message),
    )
  }
}
const handleSubmitCar = () => {
  if (formCarData.value.ID) {
    updateBlacklistCarEntry()
  } else {
    addNewBlacklistCarEntry()
  }
}

onMounted(() => {
  searchBlacklist()
})
</script>

<style scoped>
.input {
  @apply border-input bg-background placeholder:text-muted-foreground focus:ring-ring mt-1 block w-full rounded-md px-3 py-2 text-sm shadow-sm focus:outline-none focus:ring-1;
}

.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}

.checkbox {
  @apply text-primary focus:ring-primary border-input h-4 w-4 rounded;
}

.btn-sm {
  @apply px-2 py-1 text-sm;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

:deep(.dialog-from .el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}

.box-title {
  margin-bottom: 10px;
}

:deep(.box-color) {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}

.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  height: 30px;
  /* width: 150px; */
  border-radius: 4px;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

.authorize-item {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.region-item {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-around;
}
</style>
